package com.cloud.controller;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.sql.*;
import java.util.Date;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import io.jsonwebtoken.*;

@RestController
public class LoginRegisterController {

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String dbUsername;

    @Value("${spring.datasource.password}")
    private String dbPassword;

    // 从配置中读取 JWT 密钥和过期时间
    @Value("${app.jwt.secret-key}")
    private String secretKey;

    @Value("${app.jwt.expiration}")
    private long expiration;

    // 初始化 SecretKey
    private SecretKey SIGNING_KEY;

    // 修改为静态内部类，添加setters和无参构造
    public static class LoginRequest {
        private String username;
        private String password;

        public LoginRequest() {}
        public void setUsername(String username) {
            this.username = username;
        }
        public void setPassword(String password) {
            this.password = password;
        }

        public String getUsername() { return username; }
        public String getPassword() { return password; }
    }
    @PostConstruct
    public void init() {
        SIGNING_KEY = new SecretKeySpec(secretKey.getBytes(), SignatureAlgorithm.HS512.getJcaName());
    }

    // 用户注册接口
    @PostMapping("/register")
    public String register(@RequestBody LoginRequest request) {
        String username = request.getUsername();
        String password = request.getPassword();
        String encryptedPassword = encryptPassword(password);
        String userId = java.util.UUID.randomUUID().toString();

        try (Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
             PreparedStatement stmt = conn.prepareStatement("INSERT INTO user(username,password,userid) VALUES(?,?,?)")) {

            stmt.setString(1, username);
            stmt.setString(2, encryptedPassword);
            stmt.setString(3, userId);
            stmt.executeUpdate();

            return "注册成功，用户ID：" + userId;
        } catch (Exception e) {
            e.printStackTrace();
            return "注册失败：" + e.getMessage();
        }
    }

    // 用户登录接口
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody LoginRequest request) {
        String username = request.getUsername();
        String password = request.getPassword();
        String encryptedPassword = encryptPassword(password);
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM user WHERE username=? AND password=?")) {

            stmt.setString(1, username);
            stmt.setString(2, encryptedPassword);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                String userId = rs.getString("userid"); // 从结果集中获取 userid
                String token = generateJwtToken(userId); // 使用 userid 生成 JWT Token
                return ResponseEntity.ok(token); // HTTP 200 OK
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误"); // HTTP 401

            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("登录失败：" + e.getMessage());
        }
    }

    // 简单的密码加密方法（实际建议用 BCrypt）
    private String encryptPassword(String password) {
        return Integer.toHexString(password.hashCode());
    }

    // 生成 JWT Token
    private String generateJwtToken(String userId) {
        return Jwts.builder()
                .setSubject(userId) // 将 userid 存入 token 的 subject
                .claim("userid", userId) // 显式添加 userid 声明
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SIGNING_KEY)
                .compact();
    }
}
